package cn.interestingshop.servlet.client;

import cn.interestingshop.entity.Cart;
import cn.interestingshop.entity.CartGoods;
import cn.interestingshop.entity.Goods;
import cn.interestingshop.service.GoodsService;
import cn.interestingshop.service.impl.GoodsServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.List;

@WebServlet("/CartAddServlet")
public class CartAddServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //1.设置编码
        request.setCharacterEncoding("utf-8");
        response.setContentType("text/html;charset=UTF-8");
        //2.获取请求参数
        String goodsId = request.getParameter("goodsId");
        String buyNum = request.getParameter("buyNum");
        //3.调用service进行业务处理
        GoodsService service=new GoodsServiceImpl();
        Goods goods = service.selectOne(Integer.parseInt(goodsId));
        int i = insert(request, goods, Integer.parseInt(buyNum));
        //4.分析返回结果
        if(i>0){
            response.getWriter().print(true);
        }else{
            response.getWriter().print(true);
        }
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doPost(request,response);
    }

    /**
     * 加入购物车
     * @param request
     * @param goods
     * @return
     */
    public int insert(HttpServletRequest request, Goods goods,int buyNum) {
        //1.从session中获取当前登录用户购物车
        HttpSession session = request.getSession();
        Cart cart = (Cart)session.getAttribute("cart");
        if(cart==null){
            cart=new Cart();
            session.setAttribute("cart",cart);
        }
        //2.判断该商品是否已经加入购物车
        CartGoods old=null;
        List<CartGoods> cartGoodsList = cart.getCartGoods();
        for (CartGoods cartGood : cartGoodsList) {
            if(cartGood.getId()==goods.getId()){
                old=cartGood;
                break;
            }
        }
        if(old!=null){//购买过
            old.setBuyNum(old.getBuyNum()+buyNum);
            old.setSum(goods.getPrice()*buyNum);
        }else{
            old=new CartGoods();
            old.setId(goods.getId());
            old.setGoodsName(goods.getGoodsName());
            old.setPrice(goods.getPrice());
            old.setBuyNum(buyNum);
            old.setFileName(goods.getFileName());
            old.setSum(buyNum*goods.getPrice());

            cart.getCartGoods().add(old);
        }
        //计算总结
        cart.setSum(cart.getSum()+buyNum*goods.getPrice());

        return 1;
    }
}
